--
-- Author: shunguo.chen
-- Date: 2017-6-28 17:42:49
--
-- SettingBasePanel

local TabsBtn = require("app.widget.TabsBtn")
local LangMenuRender = import(".LangMenuRender")

local ClassRef = app.mvc.createPanelClass(...)

local setting

function ClassRef.create(node)
	local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.SettingBasePanel))
	if node == nil then
		ccui.Helper:doLayout(sprite)
	end
	sprite:init()
	return sprite
end

function ClassRef:_getCurLangConfig(lang)
	if not lang then
		lang = app:getCurrentLanguage()
	end
	for k , v in pairs(self._langConfig) do
		if v.key == lang then
			return v
		end
	end
end

function ClassRef:init(data)
	self.super.init(self, data)

	setting = UD.setting

	-- init btns

	self._btns = {0,0,0,0}
	for i=1,5 do
		local btn = self._ui["Panel/Panel_" .. i .. "/selected_btn"]
		self._btns[i] = btn
		btn:setTag(i)
		btn:addClickEventListener(handler(self, self.onBtnClick))
		if i == 1 then
			btn:setBright(not setting:isShowPlayerUpHead())
		elseif i == 2 then
			btn:setBright(app:isTextureHalfSizeEnable())
		elseif i == 3 then
			btn:setBright(not app:isFastFps())
		elseif i == 4 then
			btn:setBright(not setting:isAutoPlayWeather())
		elseif i == 5 then
			btn:setBright(not app:isEffectAllShow())
		end
	end

	local soundBtn = self._ui["Panel/Panel_Slider_2/Panel_tick"]
	soundBtn:setTag(6)
	soundBtn:addClickEventListener(handler(self, self.onBtnClick))
	soundBtn:findChild("selected_btn"):setBright(not AM.isMuteSound())

	local musicBtn = self._ui["Panel/Panel_Slider_3/Panel_tick"]
	musicBtn:setTag(7)
	musicBtn:addClickEventListener(handler(self, self.onBtnClick))
	musicBtn:findChild("selected_btn"):setBright(not AM.isMuteMusic())

	self._btns[6] = soundBtn
	self._btns[7] = musicBtn


	-- player num tabs
	local default
    if setting:isShowMost() then
        default = 100
    elseif setting:isShowNormal() then
        default = 50
    elseif setting:isShowLittle() then
        default = 0
    end

    local numSlider = self._ui["Panel_Slider_1/Slider"]
    numSlider:addTouchEventListener(function(sender, state)
		if state == 2 then
			local percent = sender:getPercent()
			local endPercent = percent
			local index = 1
			if percent < 25 then
				index = 1
				endPercent = 0
			elseif percent >= 25 and percent<= 75 then
				index = 2
				endPercent = 50
			else
				index = 3
				endPercent = 100
			end
			sender:setPercent(endPercent)
            self:onSwitchNum(index)
		    -- 显示人数和品质选择有关
		    if self._lvTabsBtn and not setting:isCustomVideoQuality() then
		    	self:selectLvTabs(3)
		    end
        end
    end)
    numSlider:setPercent(default)
    self._numSlider = numSlider

	-- lv tabs
	local default
    if setting:isHighVideoQuality() then
        default = 1
    elseif setting:isLowVideoQuality() then
        default = 2
    elseif setting:isCustomVideoQuality() then
        default = 3
    end
	local btns = {self._ui.Panel_tick_1, self._ui.Panel_tick_2, self._ui.Panel_tick_3}
	self._lvTabsCheckBtns = {self._ui["Panel_tick_1/selected_btn"], self._ui["Panel_tick_2/selected_btn"], self._ui["Panel_tick_3/selected_btn"]}
	self._lvTabsBtn = TabsBtn.new(btns, handler(self, self.onSwitchLv), default)



	local soundSlider = self._ui["Panel_Slider_2/Slider"]
	local musicSlider = self._ui["Panel_Slider_3/Slider"]

	soundSlider:addEventListener(function(sender, eventType)
        if eventType == 0 then
            local v = sender:getPercent()/100
            AM.setSoundVolumeMax(v)
            app:saveValue(Enums.UserDefaultKey.SoundVolumeMax,v)
        end
    end)

    soundSlider:setPercent(AM.getSoundVolumeMax()*100) 

    musicSlider:addEventListener(function(sender, eventType)
        if eventType == 0 then
            local v = sender:getPercent()/100
            AM.setMusicVolumeMax(v)
            app:saveValue(Enums.UserDefaultKey.MusicVolumeMax,v)
        end
    end)
    musicSlider:setPercent(AM.getMusicVolumeMax()*100) 	
	-- init language/other
	local publisher = app:getInnerPublisher()
	if publisher == Enums.Publisher.tencent then --tencent
		self._ui.Panel_other:setVisible(true)
		self._ui.Panel_language:setVisible(false)
		self:initLinkUrl()
	elseif publisher == Enums.Publisher.ema then --ema oversea
		self._ui.Panel_other:setVisible(false)
		self._ui.Panel_language:setVisible(true)
		self:_initLangSetting()
	else
		self._ui.Panel_other:setVisible(false)
		self._ui.Panel_language:setVisible(true)
		self:_initLangSetting()
	end

	-- 用户ID
	self._ui.tick_tlt_0:setString(string.format(L("userIDstring"), UD.player.uid))
end

--打开网络连接
function ClassRef:initLinkUrl()
	local url = {
		"http://game.qq.com/privacy_en.shtml" ,	--隐私政策
		"http://game.qq.com/contract_en.shtml",	--服务条款
		"https://game.qq.com/contract.shtml",	--腾讯游戏许可及服务协议
	}
	local btn = {}
	for i = 1 ,3 do
		local btn = self._ui["Panel_other/btn_"..i]
		if btn then
			btn:setVisible(app:isTencent())
			btn:addClickEventListener(function()
			app.channelAPI:openURL(url[i])
				end)
		end
	end
end

-- 画质
-- 1	高画质
-- 2	低画质
-- 3	自定义
function ClassRef:onSwitchLv(index)
	for i,v in pairs(self._lvTabsCheckBtns) do
		v:setBright(i~=index)
	end

	setting:setVideoQuality(index)
	if index == 1 then
		self:refreshBtn(1, true)
		self:refreshBtn(2, true)
		self:refreshBtn(3, true)
		self:refreshBtn(4, true)
		self:refreshBtn(5, true)
		self._numSlider:setPercent(100)
		self:onSwitchNum(1)
	elseif index == 2 then
		self:refreshBtn(1, false)
		self:refreshBtn(2, false)
		self:refreshBtn(3, false)
		self:refreshBtn(4, false)
		self:refreshBtn(5, false)
		self._numSlider:setPercent(0)
		self:onSwitchNum(3)
	elseif index == 3 then

	end
	UD:updateSetting(setting)
end

-- 同屏人数
-- 1	极多
-- 2	正常
-- 3	很少
function ClassRef:onSwitchNum(index)
	if index == 3 then--most 
        setting:showMostPlayer()
    elseif index == 2 then--normal
        setting:showNormalPlayer()
    elseif index == 1 then--little
        setting:showLittlePlayer()
    end
    UD:updateSetting(setting)
end

-- 1	头顶信息
-- 2	景深模式   #动态头像
-- 3	刷新频率（高）
-- 4	环境效果
-- 5	特效等级
-- 6	音效 #动态背景
-- 7	音效 #景深模式

function ClassRef:onBtnClick(sender)
	local tag = sender:getTag()
	local isBright = sender:isBright()
	self:refreshBtn(tag, isBright)

	-- 1-5和品质选择有关
	if not setting:isCustomVideoQuality() and tag <= 5 then
		self:selectLvTabs(3)
    end
end

function ClassRef:selectLvTabs(index)
    self._lvTabsBtn:setSelected(index, true)
	for i,v in pairs(self._lvTabsCheckBtns) do
		v:setBright(i~=index)
	end
end

function ClassRef:refreshBtn(index, isSelect)
	local btn = self._btns[index]
	local isBright = btn:isBright()

	if (not isBright) == isSelect then return end

	btn:setBright(not isBright)
	local isChange = true
	if index == 1 then
		setting:setShowPlayerUpHead(isSelect)
	elseif index == 2 then
		isChange = false
		app:saveValue(Enums.UserDefaultKey.TextureHalfSize, not isSelect)
	    app:updateTextureHalfSize()
	elseif index == 3 then
		isChange = false
		app:saveValue(Enums.UserDefaultKey.FpsFast, isSelect)
	    app:updateFps()
	elseif index == 4 then
		setting:setAutoPlayWeather(isSelect)
	elseif index == 5 then
		setting:setGenBattleStaticBgEnable(not isSelect)
		EFFECT_ALL_SHOW = isSelect
	elseif index == 6 then
		btn:getChildByName("selected_btn"):setBright(AM.isMuteSound())
		isChange = false
		AM.setSoundMute(not AM.isMuteSound())
	    app:saveValue(Enums.UserDefaultKey.MuteSound,AM.isMuteSound())
	elseif index == 7 then
		btn:getChildByName("selected_btn"):setBright(AM.isMuteMusic())
		isChange = false
		AM.setMusicMute(not AM.isMuteMusic())
	    app:saveValue(Enums.UserDefaultKey.MuteMusic,AM.isMuteMusic())
	end

	if isChange then
		UD:updateSetting(setting)
	end
end

function ClassRef:_createSettingLangRender()
	self._langSettingRender = LangMenuRender.create()
	self._langSettingRender:setData(self._langConfig)
	self._langSettingRender:setVisible(false)
	-- self._langSettingRender:setAnchorPoint(0, 1)
	display.nodeRemoveForNotHit(self._langSettingRender, function()
		if self._langSettingRender and self._langSettingRender:isVisible() then
			self._langSettingRender:setVisible(false)
			self._ui["Panel/Panel_language/btn_more"]:setFlippedY(false)
		end
	end)
	self._ui["Panel/Panel_language/bg"]:addChild(self._langSettingRender)
	self._langSettingRender:setCallback(handler(self, self._onSelectLang))
	local height = self._ui["Panel/Panel_language/bg"]:getContentSize().height
	self._langSettingRender:setPositionY(height)
end

function ClassRef:_onSelectLang(langConfig)
	if self._curLangConfig.key ~= langConfig.key then
		self._ui["Panel/Panel_language/language"]:setString(langConfig.name)
		local confirmDialog = display.newConfirmDialog(string.format(L("ChangeDefaultLang"), langConfig.name), function()
			app:changeDefaultLanguage(langConfig.key)
		end, function()
			self._ui["Panel/Panel_language/language"]:setString(self._curLangConfig.name)
		end)
		confirmDialog:setConfirmText(L("CommonBtnConfirm"))
		confirmDialog:setCancelText(L("CommonBtnCancel"))
		cc.Director:getInstance():getRunningScene():addChild(confirmDialog, 1000)
	end
end

function ClassRef:_initLangSetting()
	
	local LangsString = {
		CHS = L("ChineseSimplifiedLang"),
		EN = L("EnglishLang")
	}
	local langArr = app:getMultiLanguageArray()
	local curLang = app:getCurrentLanguage()

	self._langConfig = {}

	local isContainCurLang = false;
	for k ,v in pairs(langArr) do
		if not isContainCurLang and v == curLang then
			isContainCurLang = true
		end
		table.insert(self._langConfig, {name = LangsString[v] or "", key = v});
	end

	if not isContainCurLang then
		table.insert(self._langConfig, {name = LangsString[curLang] or "", key = curLang});
	end

	
	self._curLangConfig = self:_getCurLangConfig()
	if not self._curLangConfig then
		self._curLangConfig = self:_getCurLangConfig("CHS")
	end

	if #self._langConfig <= 1 then
		self._ui["Panel/Panel_language/btn_more"]:setVisible(false)
	else
		self._ui["Panel/Panel_language/btn_more"]:setVisible(true)
	end
	self._ui["Panel/Panel_language/language"]:setString(self._curLangConfig.name)

	self._ui["Panel/Panel_language/btn_more"]:addClickEventListener(function()
		if not self._langSettingRender then
			self:_createSettingLangRender()
		end
		if self._langSettingRender:isVisible() then
			self._langSettingRender:setVisible(false)
			self._ui["Panel/Panel_language/language"]:setVisible(true)
			self._ui["Panel/Panel_language/btn_more"]:setFlippedY(false)
		else
			self._langSettingRender:setVisible(true)
			self._ui["Panel/Panel_language/language"]:setVisible(false)
			self._ui["Panel/Panel_language/btn_more"]:setFlippedY(true)
		end
	end)

end

return ClassRef